package com.ludomancy.starwave;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.Vector;

import com.ludomancy.gamelib.Button;
import com.ludomancy.gamelib.GameCanvas;
import com.ludomancy.gamelib.Randomizer;
import com.ludomancy.gamelib.ResourceManager;
import com.ludomancy.gamelib.Utils;
import com.ludomancy.gamelib.Widget;
import com.ludomancy.gamelib.Button.ButtonListener;

public class GameWonWidget extends Widget implements ShipTypes, ButtonListener
{
	private static final int[] shipTypes = new int[]{DEF,MIN,WMD};
	private Vector ships = new Vector();
	private static final long UPDATE_TIMER = 30;
	private static final long NEWSHIP_TIMER = 120;
	private long lastUpdate;
	private long lastNewShipUpdate;
	private Button restart;
	
	public GameWonWidget(Widget parent)
	{
		super(parent, new Rectangle(0,0,GameCanvas.screen.getWidth(), GameCanvas.screen.getHeight()));
//		restart = new Button(this, new Rectangle(0, GameCanvas.screen.getHeight()- 25 - 6, GameCanvas.screen.getWidth()+1, 25), "Restart", this);
	}
	
	public void update()
	{
		if(System.currentTimeMillis() - lastNewShipUpdate > NEWSHIP_TIMER)
		{
			int newType = Randomizer.getRandom(0, shipTypes.length-1);
			Ship newShip = Ship.createPrototype(shipTypes[newType], new Player(1), 0, 0);
			newShip.px = -Settings.TILE_SIZE-Randomizer.getRandom(32, 64);
			newShip.py = Randomizer.getRandom(50, getHeight()-33);
			ships.add(newShip);
			lastNewShipUpdate = System.currentTimeMillis();
		}
		if(System.currentTimeMillis() - lastUpdate > UPDATE_TIMER)
		{
			
			for (int i = 0; i < ships.size();)
			{
				Ship ship = (Ship) ships.elementAt(i);
				ship.px += LAST - ship.type + 1;
				if(ship.px > getWidth())
				{
					ships.removeElementAt(i);
				}
				else
				{
					i++;
				}
			}
			lastUpdate = System.currentTimeMillis();
		}
	}
	
	public void paint(Graphics g)
	{
		Image map = ResourceManager.getImage("background.png");
		g.drawImage(map, 0, 0, null);
		g.setFont(((StarwaveTheme)getTheme()).textFont);
		g.setFont(((StarwaveTheme)getTheme()).idleBarFont);
		Utils.drawMultiline(g, "We managed to repel the invasion. Now, it's time to pay \"Earth\" a visit to return the favor...", getWidth()-10, 5, 5);
		for (int i = 0; i < ships.size(); i++)
		{
			Ship ship = (Ship) ships.elementAt(i);
			ship.paint(g, ship.px, ship.py);
		}		
	}

	public void onPress(Button widget)
	{
		if(widget == restart)
		{
			StarWaveApplet.app.restart();
		}
	}
}
